package com.example.oop.Service;

import com.example.oop.POJO.User;
import com.example.oop.Repository.RepositoryManager;
import com.example.oop.Repository.UserRepository;
import com.example.oop.Utils.Response;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

public class LogoutService {
    private UserRepository userRepository;

    public LogoutService() {
        this.userRepository = RepositoryManager.userRepository;  //手动从容器中获取Repository
    }

    //    实现登出操作
    public JSONObject doLogout(JSONObject logoutRequest) throws JSONException {
        synchronized (RepositoryManager.userRepository) {
            JSONObject response;  //定义用来响应的JSON

            String username = logoutRequest.optString("username", "");  //获取用户名

            User user = null;  //根据用户名获取用户信息
            if (userRepository.findByUsername(username).isPresent()) {
                user = userRepository.findByUsername(username).get();  //从数据库中获取用户
            }

            // 对当前用户进行登出操作
            user.setStatus(false);  //设置用户登出状态
            user.setLogoutTime(new Date());  //设置登出时间
            userRepository.save(user);  //保存当前用户信息

            //删除用户会话（包含其消息）
//            if (chatRoomId != null && !chatRoomId.equals("")) {
//                ChatRoomManager.i.deleteChatRoom(Integer.parseInt(chatRoomId));
//            }

            System.out.println("用户" + username + "与服务器断开连接！");

            // 响应消息
            response = Response.getJsonObject("0", "登陆退出成功！");
            JSONObject jsonData = new JSONObject();

            response.put("status", 0);
            response.put("data", jsonData);

            return response;
        }
    }
}
